$(document).ready(function(){
	$('#fblogin').click(function(){
		fbLogin();
	});
    $('#logout').click(function(){
        location.href = BASE_URL + '/logout.php';
    });
	$('.vote-listing').click(function(){
		var permalink = $(this).attr('rel');
	});

});
var OAUTHURL    =   'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL    =   'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE       =   'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID    =   '456392668422-nunr2i42sj1osmm54pv60k26mnjl1tha.apps.googleusercontent.com';
var REDIRECT    =   BASE_URL + '/oauth.php'
var LOGOUT      =   'http://accounts.google.com/Logout';
var TYPE        =   'token';
var _url        =   OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn    =   false;


function login() {
    var win         =   window.open(_url, "windowname1", 'width=800, height=600'); 

    var pollTimer   =   window.setInterval(function() { 
        try {
            console.log(win.document.URL);
            if (win.document.URL.indexOf(REDIRECT) != -1) {
                window.clearInterval(pollTimer);
                var url =   win.document.URL;
                acToken =   gup(url, 'access_token');
                tokenType = gup(url, 'token_type');
                expiresIn = gup(url, 'expires_in');
                win.close();

                validateToken(acToken);
            }
        } catch(e) {
        }
    }, 500);
}

function validateToken(token) {
    $.ajax({
        url: BASE_URL + '/oauth.php',
        data: {"token" : token},
        type: 'POST',
        success: function(responseText){  
            if(responseText === '1'){
				location.href = BASE_URL;
			}
        }
    });
}

function fbLogin(){
	 FB.login(function(response) {
	   if (typeof response.authResponse != 'undefined' && typeof response.authResponse.accessToken != 'undefined') {
			$.ajax({
				url: BASE_URL + '/fbauth.php',
				type: 'POST',
				data: {token: response.authResponse.accessToken},
				success: function(response){
					//console.log(response);
				  if(response === '1'){
					location.href = BASE_URL;
				  }
				}
			});
	   }
	}, {scope: 'email', response_type: 'code'});
}
